define('pc/js/mod/write/Tag', ['pc/js/mod/write/tag.css'], function(css){

var Tag = function(id) {
    this.doc = document;

    this.wrapper = this.doc.getElementById(id);
    this.input = null;
    this.tagWrapper = null;
    this.html =
'<div>' +
    '<span></span>' +
    '<input type="text" class="writing-addtag-input" maxlength="10"/>' +
    '<span>&nbsp;按回车键添加标签</span>' +
'</div>';

    // ,a,b,c,
    this.tags = ',';
    this.maxTags = 3;
    this.tagNumber = 0;

    this.init();
    this.bindEvent();
};
Tag.prototype = {
    constructor: Tag,

    init: function() {
        this.wrapper.innerHTML = this.html;

        this.input = this.wrapper.querySelector('input');
        this.tagWrapper = this.wrapper.querySelector('span');
    },
    bindEvent: function() {
        var _self = this;

        // add tag
        this.input.onkeyup = function(e) {
            if(13 === e.keyCode) {
                if(_self.tagNumber >= _self.maxTags) {
                    XUI.toast.error('标签个数已达上限');

                    return;
                }

                _self.tags = _self.tags + _self.input.value + ',';
                _self.input.value = '';
                _self.renderTag();
            }
        };

        // del tag
        this.tagWrapper.onclick = function(e) {
            var t = e.target;
            var v = '';

            if('A' === t.nodeName.toUpperCase()) {
                v = t.getAttribute('data-tag');

                _self.tags = _self.tags.replace(',' + v + ',', ',');
                _self.renderTag();
            }
        };
    },

    renderTag: function() {
        var arr = this.tags.split(',');
        var ret = '';
        var num = 0;

        for(var i=0,len=arr.length; i<len; i++) {
            if('' === arr[i]) {
                continue;
            }

            num += 1;

            ret += '<a href="javascript:;" data-tag="'+ arr[i] +'" class="writing-tag">'+ arr[i] +'</a>';
        }

        this.tagNumber = num;

        this.tagWrapper.innerHTML = ret;
    },

    getValue: function() {
        var tags = this.tags;

        tags = tags.replace(/^,+/, '').replace(/,+$/, '');

        return tags;
    },
    setValue: function(tags) {
        this.tags = this.tags + tags + ',';
        this.renderTag();
    }
};

return {
    init: function(id) {
        return new Tag(id);
    }
};
});

